import React, {useEffect, useRef, useState, Fragment} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable, {ActionType} from '@ant-design/pro-table';
import {entityInfo, entityPage, entityUpdate, entityDel, entityAdd} from "./service";
import {Divider, Button, message, Tooltip, Modal} from "antd";
import CreateForm from "./components/CreateForm";
import UpdateForm from "./components/UpdateForm";
import {DeleteOutlined, FormOutlined, PlusOutlined} from "@ant-design/icons/lib";
import {AssemblyParams, AssemblyProps} from "@/pages/DynamicTable/data";
import {TableListItem} from "@/pages/AuthConfig/data";
import {formPropsLayout} from "@/utils/tableUtils";

let assemblyS: AssemblyParams;

const handleUpdate = async (fields: TableListItem) => {
  const hide = message.loading('正在更新');
  const res = await entityUpdate(assemblyS.name, fields);
  hide();
  if (res.code == 10000) {
    message.success('更新成功');
    return true;
  }
  message.error('更新失败，请重试');
  return false
};


const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');

  const res = await entityAdd(assemblyS.name, {...fields});
  hide();
  if (res.code == 10000) {
    message.success('添加成功');
    return true;
  }
  message.error('更新失败，请重试');
  return false;
};

const handleRemove = async (id: number) => {
  const hide = message.loading('正在删除');

  const res = await entityDel(assemblyS.name, {id: id});
  hide();
  if (res.code == 10000) {
    message.success('删除成功，即将刷新');
    return true;
  }
  message.error('删除失败，请重试');
  return false;

};


const DynamicTable: React.FC<AssemblyProps> = (props) => {
  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState<any>({});


  const {assembly} = props;


  const columns: any[] = assembly.columns ? assembly.columns : [];

  const tableColumns: any[] = [];

  const updateColumns: any[] = [];

  const createColumns: any[] = [];


  for (let column of columns) {
    if (column.init) {
      column.initialValue = stepFormValues[column.dataIndex]
    }

    // 修改验证规则
    if (column.formItemProps && column.formItemProps.rules) {
      for (let rule of column.formItemProps.rules) {
        if (!rule.type) continue;

        if (rule.type == "mobile") {
          rule.pattern = new RegExp(/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/);
          delete rule.type;
        } else if (rule.type == "idCard") {
          rule.pattern = new RegExp(/(^\d{18}$)|(^\d{17}(\d|X|x)$)/);
          delete rule.type;
        }
      }
    }

    // table 控制
    let tableColumn = column;
    if (tableColumn.hideInTable === false) {
      tableColumns.push(tableColumn);
    }

    // 创建表单控制
    let createForm = column;

    if (createForm.showCreateForm) {
      createForm.hideInForm = false;
      createColumns.push(createForm);
    }

    let updateForm = column;

    // 修改表单控制
    if (updateForm.showUpdateForm) {
      updateForm.hideInForm = false;
      updateColumns.push(updateForm);
    }

  }


  useEffect(() => {
    assemblyS = assembly;
  }, [assembly])


  if (assembly.updateControl || assembly.deleteControl) {
    tableColumns.push({
      title: '操作',
      dataIndex: 'option',
      hideInSearch: true,
      hideInForm: true,
      render: (text: any, record: any) => (
        <Fragment>
          {assembly.updateControl &&
          <a
            onClick={() => {
              entityInfo(assembly.name, {id: record.id}).then((res: any) => {
                if (res.code === 10000) {
                  setStepFormValues(res.data);
                  handleUpdateModalVisible(true);
                }
              })
            }}
          >
            <Tooltip title="编辑">
              <FormOutlined/>
            </Tooltip>
          </a>
          }
          {assembly.updateControl && assembly.deleteControl && <Divider type="vertical"/>}
          {assembly.deleteControl &&
          <a onClick={() => removeItem(record.id)}>
            <Tooltip title="删除">
              <DeleteOutlined/>
            </Tooltip>
          </a>
          }
        </Fragment>
      ),
    });
  }

  const removeItem = (id: number) => {
    Modal.confirm({
      title: '确认',
      content: '是否确认删除？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        let promise = await handleRemove(id);
        if (promise && actionRef.current) actionRef.current.reload()
      },
    });
  };


  return (
    <PageContainer>
      <ProTable<any>
        headerTitle={`${assembly.showName || ''}列表`}
        actionRef={actionRef}
        toolBarRender={() => assembly.addControl ? [
          <Button type="primary" onClick={() => handleModalVisible(true)}>
            <PlusOutlined/> 新建
          </Button>,
        ] : []}
        rowKey='id'
        request={(params) => entityPage({...params, currPage: params.current}, assembly.name).then(res => {
          const result = {data: [], total: 0, success: false};
          if (res.code === 10000) {
            result.data = res.data.rows ?? [];
            result.total = res.data.totalCount;
            result.success = true;
          }
          return result
        })}
        search={assembly.queryControl ? {} : false}
        columns={tableColumns}
      />
      <CreateForm title={`新建${assembly.showName || ''}`} onCancel={() => handleModalVisible(false)}
                  modalVisible={createModalVisible}>
        <ProTable<any, any>
          onSubmit={async (value) => {
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="key"
          type="form"
          columns={createColumns}
          rowSelection={{}}
          form={formPropsLayout}
        />
      </CreateForm>
      {stepFormValues && Object.keys(stepFormValues).length && (
        <UpdateForm
          title={`更新${assembly.showName || ''}`}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
        >
          <ProTable<any, any>
            onSubmit={async (value) => {
              value.id = stepFormValues.id;
              const success = await handleUpdate(value);
              if (success) {
                handleUpdateModalVisible(false);
                setStepFormValues({});
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}
            rowKey="key"
            type="form"
            columns={updateColumns}
            rowSelection={{}}
            form={formPropsLayout}
          />
        </UpdateForm>
      )}
    </PageContainer>
  );
};

export default DynamicTable;
